<template>
  <div class="circleBox">
    <div ref="container" class="circle"></div>
    <div class="desc">{{ `${(+props.value).toFixed(2)}%` }}</div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted } from 'vue'

const container = ref()
const props = defineProps({
  value: Number,
  color: {
    default: '#2ce385',
    type: String
  }
})

const option = {
  animation: true,
  series: [
    {
      type: 'gauge', // 仪表盘图
      startAngle: 90,
      endAngle: -270,
      min: 0,
      max: 1,
      radius: '100%',
      center: ['50%', '50%'],
      progress: {
        // 进度环
        roundCap: 'true',
        show: true,
        width: 10,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                //进度环的渐变色
                offset: 0,
                // color: '#2ce385' // 0% 处的颜色
                color: props.color // 0% 处的颜色
              },
              {
                offset: 1,
                color: props.color // 100% 处的颜色
              }
            ]
          }
        }
      },
      axisLine: {
        // 背景环
        roundCap: 'true',
        lineStyle: {
          width: 10,
          // color: [
          //   [0, '#CCEFDD'],
          //   [1, '#CCEFDD']
          // ]
          color: [
            [0, '#fff'],
            [1, '#fff']
          ]
        }
      },
      pointer: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: { show: false },
      detail: { show: false },
      data: [
        {
          value: props.value / 100 // 进度值，最高为1
        }
      ]
    }
  ]
}

const init = () => {
  const myChart = echarts.init(container.value, null, { devicePixelRatio: 2.5 })
  myChart.setOption(option)
  window.addEventListener('reset', () => myChart.resize())
}

onMounted(() => {
  init()
  window.addEventListener('resize', () => init())
})
</script>

<style scoped lang="scss">
.circleBox {
  position: relative;
  width: 100%;
  height: 100%;

  .circle {
    width: 100%;
    height: 100%;
    color: #fff;
    position: relative;
  }

  .desc {
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 20px;
    font-weight: 700;
    transform: translate(-50%, -50%);
  }
}
</style>
